import {
  getPermissionList,
  delPermission
} from '@/api/permission'
import {
  tranListToTreeData
} from '@/utils'
import EditPermission from './components/edit-permission.vue'
// 导入检测按钮权限的mixins
import checkPermission from '@/mixins/checkPermission'
export default {
  components: {
    EditPermission
  },
  // 注册mixins
  mixins: [checkPermission],
  data() {
    return {
      // 权限树形数据
      treeList: [],
      // 权限列表数据
      list: [],
      loading: false
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 删除权限
    async deletePermission(id) {
      // 如果当前待删除的权限有子权限，提示不能删除
      const result = this.list.filter(item => item.pid === id)
      if (result.length > 0) {
        return this.$message.warning('该权限下有子权限，请先删除子权限再删除')
      }
      // 提示
      await delPermission(id)
      this.$message.success('删除权限成功')
      this.getPermissionList()
    },
    // 打开编辑或者添加权限的对话框
    showEditPerDialog({
      type,
      id,
      level
    }) {
      this.$refs.editPerRef.open({
        type,
        id,
        level
      })
    },

    async getPermissionList() {
      this.loading = true
      const list = await getPermissionList()
      this.list = list
      // 查询数据并转换为树形表格要求的树形数据
      this.treeList = tranListToTreeData(list, '0')
      this.loading = false
    },
    // 给某一行设置class类名
    rowClass({
      row
    }) {
      // type为1位路由权限，type为2代表按钮权限，type为3代表api权限
      if (row.type === 3) {
        // 用来隐藏三级
        return 'hide'
      } else if (row.type === 2) {
        // 用来隐藏二级前面的图标
        return 'icon-hide'
      } else {
        return ''
      }
    }
  }
}
